<style scoped>
.storeSales {
  margin-right: 15px;
  padding: 0 15px;
  background-color: white;
  height: 91.5vh;
  position: relative;
}
.cog-top {
  padding-top: 10px;
  border-bottom: 2px solid #f4f4f4;
}
.cog-top div {
  margin-bottom: 5px;
  white-space: nowrap;
}
.cog-top p:first-child {
  line-height: 30px;
  display: inline-block;
  margin-right: 5px;
}
.cog-top p:not(:first-child) {
  line-height: 30px;
  display: inline-block;
  width: 70px;
  text-align: right;
  margin-right: 10px;
}
.top-inp {
  width: 160px;
}
.cog-btn {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
}
.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
.cog-tab {
  display: flex;
}
.cog-tab > div:first-child {
  padding-right: 20px;
  width: 50%;
  border-right: 2px solid #f4f4f4;
}
.cog-tab > div:last-child {
  padding-left: 20px;
  width: 50%;
}
</style>

<style>
.storeSales .el-input {
  height: 30px;
}
.storeSales .cog-top .el-input__inner {
  height: 30px;
}
.storeSales .el-checkbox.is-bordered {
  padding: 5px 10px 0 10px;
  height: 30px;
}
.storeSales .cog-top .el-date-editor .el-range__icon {
  line-height: 23px;
}
.storeSales .cog-top .el-date-editor .el-range-separator {
  line-height: 23px;
  width: 8%;
}
.storeSales .el-input__icon {
  line-height: 30px;
}
.storeSales .el-date-editor.el-input,
.storeSales .el-date-editor.el-input__inner {
  width: 160px;
}
</style>

<template>
  <div class="storeSales">
    <!-- <div class="cog-top">
      <div>
        <p>销售日期</p>
        <el-date-picker 
          v-model="inputDate"
          type="date" 
          placeholder="选择日期" 
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
        <p>VIP</p>
        <el-input class="top-inp" v-model="vip"></el-input>
        <p>主推</p>
        <el-select class="top-inp" v-model="primaryClerk">
          <el-option v-for="item in clerkList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <p>次推</p>
        <el-select class="top-inp" v-model="secondaryClerk">
          <el-option v-for="item in clerkList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <p>款号</p>
        <el-input class="top-inp" v-model="kindsNumber"></el-input>
        <p>折扣</p>
        <el-input class="top-inp" v-model="discount"></el-input>
        <p>实收单价</p>
        <el-checkbox v-model="checked" border></el-checkbox>
        <el-input class="top-inp" v-model="actualPayment" style="width: 113px;margin-left:10px;" :disabled="!checked"></el-input>
      </div>
      <div>
        <p>销售序号</p>
        <el-input class="top-inp" v-model="sequence"></el-input>
        <p>应收</p>
        <el-input class="top-inp" v-model="shouldReceive"></el-input>
        <p>抹零</p>
        <el-input class="top-inp" v-model="preferential"></el-input>
        <p>兑换</p>
        <el-input class="top-inp" v-model="conversion"></el-input>
        <p>收现</p>
        <el-input class="top-inp" v-model="receive"></el-input>
        <p>转账</p>
        <el-input class="top-inp" v-model="transfer"></el-input>
        <p>账户余额</p>
        <el-input class="top-inp" v-model="balance"></el-input>
      </div>
    </div> -->
    <div class="cog-btn">
      <div>
        <el-button
          :disabled="isRegular"
          @click="
            () => {
              ;(this.showNew = true),
                (this.title = '新建'),
                (this.title1 = '22')
            }
          "
          icon="el-icon-plus"
          type="primary"
          >新增</el-button
        >
        <!-- <el-button @click="settleAccounts" icon="el-icon-bank-card">结账</el-button> -->
        <el-button
          icon="el-icon-circle-check"
          @click="Confirm"
          :disabled="Dis || isRegular"
          >确认</el-button
        >
        <el-button :disabled="isRegular" @click="ticket" icon="el-icon-printer"
          >打印小票</el-button
        >
        <el-button
          @click="Del"
          icon="el-icon-delete"
          :disabled="Dis || isRegular"
          >删单</el-button
        >
        <el-button
          icon="el-icon-circle-plus-outline"
          @click="Supplement"
          :disabled="Dis || isRegular"
          >补单</el-button
        >
        <el-date-picker
          style="display: none"
          v-model="time"
          type="date"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </div>
      <div>
        <el-checkbox v-model="twoDimensional" border>二维</el-checkbox>
      </div>
    </div>
    <div class="cog-tab">
      <div>
        <el-table
          :header-cell-style="{
            background: '#f4f4f4',
            padding: 0,
            height: '40px'
          }"
          :cell-style="{ padding: 0, height: '26px' }"
          highlight-current-row
          :data="tableData1"
          :summary-method="getList"
          @row-click="rowClick"
          @row-dblclick="dbClick"
          :row-class-name="rowClassName"
          style="width: 100%"
          height="75vh"
          show-summary
        >
          <el-table-column
            prop="settleAccounts"
            label="已结账"
            width="80px"
          ></el-table-column>
          <el-table-column
            prop="affirm"
            label="已确认"
            width="80px"
          ></el-table-column>
          <el-table-column
            prop="vipSellSequence"
            label="单号"
            width="120px"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="sellTime"
            label="日期"
            width="160"
          ></el-table-column>
          <el-table-column
            prop="number"
            label="数量"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="money"
            label="金额"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="preferential"
            label="抹零"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="payg"
            label="收现"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="main"
            label="主推"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="minor"
            label="次推"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="integralNumber"
            label="积分"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="cashCoupon"
            label="现金券"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="exchange"
            label="兑换"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="vip"
            label="VIP"
            width="115px"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
      </div>
      <div>
        <el-table
          :header-cell-style="{
            background: '#f4f4f4',
            padding: 0,
            height: '40px'
          }"
          :cell-style="{ padding: 0, height: '26px' }"
          highlight-current-row
          :data="tableData2"
          style="width: 100%"
          height="700"
        >
          <template v-for="i in knhList">
            <el-table-column
              :prop="i.prop"
              :label="i.label"
              :width="i.width"
              :key="i.prop"
            >
            </el-table-column>
          </template>
        </el-table>
      </div>
    </div>

    <foot-view class="footView">
      <div slot="text">
        <!-- <el-popover placement="top-start" width="120" max-height="100px" trigger="click">
          <el-checkbox-group v-model="selectHeaderList">
            <el-checkbox v-for="i in headerList" :label="i.value" :key="i.value" style="margin-bottom:7px"></el-checkbox>
          </el-checkbox-group>
          <i slot="reference" class="el-icon-date">表头配置</i>
        </el-popover> -->
        <span>数据库：{{ jxQuarter }}</span>
        <!-- <span>操作员：{{operator}}</span>
        <span>记录数：{{amount}}</span> -->
      </div>
    </foot-view>

    <new-vs
      v-if="showNew"
      :sendData="sendData"
      :clerkList="clerkList"
      :flag="showNew"
      :title="title"
      :title1="title1"
      :customerNo="customerNo"
      @inpNumChange="
        () => {
          this.inpList = this.getInput()
        }
      "
      @save="save"
      @determine="
        () => {
          this.title1 = ''
        }
      "
      @closeNew="
        () => {
          ;(this.showNew = false), this._getShopSale(), (this.title1 = '')
        }
      "
      @saveNew="saveNew"
    >
    </new-vs>
    <div id="L" v-show="false"></div>
    <print-ticket v-show="false"></print-ticket>
  </div>
</template>

<script>
import footView from '../../../components/FootView'
const resources1 = require('../../../config/print.js')
import printTicket from '../../../components/ticketPrint'

import { getClient } from '../../../network/client'
import { getBranded } from '../../../network/branded'
import { getArtNo } from '../../../network/artNo'
import { select } from '../../../network/customerOrderTotal'
import { getCommodityType } from '../../../network/commodity'

import today from '../../../components/mixins/today'
import newVs from './childComp/newVs'
import {
  getShopSale,
  DeleteSell,
  confirm,
  getShop
} from '../../../network/shop'
import { confirmOrder } from '../../../network/manufacturerOrder'
import enterUp from '../../../components/mixins/enterUp'
export default {
  name: 'store_sales_s',
  mixins: [today, enterUp],
  components: {
    footView,
    newVs,
    printTicket
  },
  data() {
    return {
      directSaleNo: '',
      inpList: [],
      isRegular: false,
      title1: '',
      Dis: false,
      jxQuarter: null,
      operator:null,
      // jxQuarter: document.cookie.match(
      //   new RegExp('jxQuarter' + name + '=([^;]*)(;|$)')
      // )[1],
      // operator: document.cookie.match(RegExp('jxUser' + '=([^;]+)'))[1],
      // twoList: [],
      saveList: [],
      title: '',
      time: '',
      showNew: false,
      sendData: {},

      inputDate: this.searchDateWithHour(),
      vip: '',
      primaryClerk: '',
      secondaryClerk: '',
      clerkList: [],
      kindsNumber: '',
      discount: '',
      checked: false,
      actualPayment: '',
      sequence: '',
      shouldReceive: '',
      preferential: '',
      conversion: '',
      receive: '',
      transfer: '',
      balance: '',
      twoDimensional: false,

      tableData1: [],
      tableData2: [],
      // 右总表
      kindsNumberList: [],
      // 右二维表
      styleNumberList: [],

      knhList: [],
      knhList1: [
        { prop: 'kindsNumber', label: '款号', width: '140' },
        { prop: 'colorName', label: '颜色', width: '120' },
        { prop: 'size', label: '尺码编号', width: '' },
        { prop: 'number', label: '数量', width: '' },
        { prop: 'sellPrice', label: '售价', width: '' },
        { prop: 'discount', label: '折数', width: '' },
        { prop: 'onePrice', label: '单价', width: '' },
        { prop: 'money', label: '金额', width: '' },
        { prop: 'commodityName', label: '品名', width: '' },
        { prop: 'brandeName', label: '品牌', width: '' },
        { prop: 'enteringTime', label: '录入时间', width: '160' }
      ],
      knhList2: [
        { prop: 'typeNumber', label: '型号', width: '' },
        { prop: 'colorName', label: '颜色', width: '' },
        { prop: 'c05', label: 'C05', width: '' },
        { prop: 'c07', label: 'C07', width: '' },
        { prop: 'c09', label: 'C09', width: '' },
        { prop: 'c11', label: 'C11', width: '' },
        { prop: 'c13', label: 'C13', width: '' },
        { prop: 'c15', label: 'C15', width: '' },
        { prop: 'c17', label: 'C17', width: '' },
        { prop: 'c19', label: 'C19', width: '' },
        { prop: 'c21', label: 'C21', width: '' },
        { prop: 'c23', label: 'C23', width: '' },
        { prop: 'f', label: 'F', width: '' },
        { prop: 'subtotal', label: '小计', width: '' },
        { prop: 'sellingPrice', label: '售价', width: '' }
      ],
      det: {},
      detail: [],
      vipSellSequence: '',

      // 设置表头
      selectHeaderList: [],
      headerList: [],
      jz: ''
    }
  },
  watch: {
    twoDimensional(a, b) {
      if (a) {
        this.knhList = this.knhList2
        if (this.tableData2 != '') {
          var nList = []
          for (let c of this.twoList) {
            // console.log(c.vipSellSequence)
            if (this.vipSellSequence == c.vipSellSequence) {
              nList.push(c)
            }
            this.tableData2 = nList
          }
        }
      } else {
        this.knhList = this.knhList1
        if (this.tableData2 != '') {
          var mList = []
          for (let c of this.saveList) {
            if (this.vipSellSequence == c.vipSellSequence) {
              mList.push(c)
            }
            this.tableData2 = mList
          }
        }
      }
    }
  },
  methods: {
    //列印小票
    ticket() {
      if (this.tableData2 == '') {
        this.$message.warning('请选中左表数据')
        return
      }
      let VIP = this.tableData1[0].vip
      let totalSellPrice = 0
      let totalNumber = 0
      console.log(totalSellPrice, totalNumber)
      // 的到一个div作为答应的容器
      let printBody = document.getElementById('L')
      // 在这个容器里面创建新的打印元素
      let printHead = document.createElement('div')
      printHead.innerHTML = `
        <span class="Head">店铺销售单</span>
        <div class="dTop" style:"display:flex;">
          <p>VIP：${VIP}</p>
          <p>销售序号：${this.vipSellSequence}</p>
        </div>
      `
      printHead.style.pageBreakBefore = 'always' //style="page-break-after:always"意思是下一行开始分页。 是css打印的一种格式。
      //  body里面插入动态创建的div(printHead)
      printBody.appendChild(printHead)
      let printTables = document.getElementById('printTables')

      let length = this.tableData2.length
      for (let index = 0; index < length; index++) {
        const e = this.tableData2[index]
        // 在表格中插入一个新行
        let row1 = printTables.insertRow()
        // insertCell() 方法用于在 HTML 表的一行的指定位置插入一个空的 <td> 元素。
        row1.insertCell(0).innerHTML = index + 1
        row1.insertCell(1).innerHTML = e.kindsNumber
        row1.insertCell(2).innerHTML = e.number
        row1.insertCell(3).innerHTML = e.onePrice
        totalSellPrice += Number(e.onePrice)
        totalNumber += Number(e.number)
      }
      // body里面再放一个table表格
      printBody.appendChild(printTables)
      // 底部再创建一个div,放售价
      let printBottom = document.createElement('div')
      printBottom.innerHTML = `
        <p>售价合计：${totalSellPrice}              数量：${totalNumber}<p>
      `
      printBody.appendChild(printBottom)
      // 得到div的元素里面的所有标签innerHTML
      let printHtml = document.getElementById('L').innerHTML
      let wind = window.open(
        '',
        'newwindow',
        'height=500, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no'
      )
      // 把得到的所有的标签，放在要打印的页面上body
      wind.document.body.innerHTML = printHtml
      let style = document.createElement('style')
      style.type = 'text/css'
      style.innerHTML = resources1.printCss
      // 这里是加样式css
      wind.document.head.appendChild(style)
      wind.print()
    },

    Confirm() {
      if (this.vipSellSequence == '') {
        this.$message.warning({ message: '请选中一条数据确认', offset: 400 })
        return
      }
      confirm({ vipSellSequence: this.vipSellSequence }).then((res) => {
        console.log(res.data)
        if (res.data.code == 200) {
          this.$message.success({ message: '确认成功', offset: 400 })
          // this._getShopSale()
        }
      })
    },
    Supplement() {
      console.log(JSON.stringify([this.det]))
      if (this.detail == '') {
        this.$message.warning({ message: '请选择一条数据补单' })
        return
      }
      // if(this.jz == '已结账'){
      //   this.$message.warning({message:'此单已结账，不可补单'})
      //   return
      // }
      this.title = '补单'
      this.showNew = true
    },
    //指定列和计
    getList(param) {
      // console.log(this.zt)
      if (this.zt == 'null') {
        return
      } else {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          const values = data.map((item) => Number(item[column.property]))
          if (
            column.property === 'number' ||
            column.property === 'money' ||
            column.property === 'preferential' ||
            column.property === 'payg'
          ) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index]
          }
        })
        return sums
      }
    },
    // 数据变动

    rowClick(e) {
      this.jz = e.settleAccounts
      this.detail = [e]
      this.det = e
      this.sendData = e
      this.clerkList = []

      if (e.affirm == 1 || e.affirm == '已确认') {
        this.Dis = true
      } else {
        this.Dis = false
      }

      this.vipSellSequence = e.vipSellSequence
      this.tableData2 = []
      if (this.twoDimensional == false) {
        this.saveList.forEach((element) => {
          if (e.vipSellSequence == element.vipSellSequence) {
            this.tableData2.push(element)
          }
        })
      } else {
        this.twoList.forEach((element) => {
          if (e.vipSellSequence == element.vipSellSequence) {
            this.tableData2.push(element)
          }
        })
      }

      for (let r of this.tableData2) {
        if (e.vipSellSequence == r.vipSellSequence) {
          this.clerkList.push(r)
        }
      }
    },

    dbClick(e) {
      console.log(e)
      if (e.settleAccounts == '未结账') {
        this.title = '编辑'
        console.log(e.affirm)
        if (e.affirm == '已确认') {
          this.title1 = '00'
        } else {
          this.title1 = '11'
        }
        this.showNew = true
        this.sendData = {}
        this.sendData = e
        this.clerkList = []
        for (let r of this.tableData2) {
          if (e.vipSellSequence == r.vipSellSequence) {
            this.clerkList.push(r)
          }
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      //   row.xh = rowIndex + 1
      //   // console.log(row,rowIndex)
    },
    Del() {
      // this.tableData1.splice(this.det.xh-1,1)
      if (JSON.stringify(this.det).replace(/\{|}/g, '') == '') {
        this.$message.warning({ message: '请选择一条删除' })
        return
      }
      for (let r of [this.det]) {
        // if(r.sellTime.slice(0,10) != this.time.slice(0,10)){
        //   this.$message.warning({message:'只能删除当天数据'});
        //   return
        // }
        // if(r.settleAccounts == '已结账'){
        //   this.$message.warning({message:'不能删除已结账数据'});
        //   return
        // }
        for (let k of [this.det]) {
          k.sellTime = k.sellTime + ' 00:00:00'
        }
        if (r.settleAccounts == '未结账') {
          r.settleAccounts = 0
        }
        if (r.affirm == '未确认') {
          r.affirm = 0
        }
      }
      this.$confirm('是否删除本条的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(this.det)
          DeleteSell(this.det).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.$message.success({ message: '删除成功' })
              this._getShopSale()
              this.tableData2 = []
            } else {
              this.$message.error({ message: '删除失败' })
              for (let t of [this.det]) {
                if (t.settleAccounts == 0) {
                  t.settleAccounts = '未结账'
                }
                if (t.affirm == 0) {
                  t.affirm = '未确认'
                }
                t.sellTime = t.sellTime.slice(0, 10)
              }
            }
          })
        })
        .catch(() => {
          for (let t of [this.det]) {
            if (t.settleAccounts == 0) {
              t.settleAccounts = '未结账'
            }
            if (t.affirm == 0) {
              t.affirm = '未确认'
            }
            t.sellTime = t.sellTime.slice(0, 10)
          }
        })
    },

    saveNew() {},
    save(data) {
      this.tableData1 = []
      for (let a of data) {
        this.vipSellSequence = a.vipSellSequence
        if (a.settleAccounts == 0) {
          a.settleAccounts = '未结账'
        } else {
          a.settleAccounts = '已结账'
        }
        if (a.affirm == 0) {
          a.affirm = '未确认'
        } else {
          a.affirm = '已确认'
        }
      }
      data.forEach((e) => {
        if (e.recharge == 0) {
          this.tableData1.push(e)
        }
      })
      // console.log(data)
      // console.log(this.tableData1)
    },
    _getShopSale() {
      if (this.vipSellSequence == '') {
        return
      }
      getShopSale({
        vipSellSequence: this.vipSellSequence,
        directSaleNo: this.customerNo
      }).then((res) => {
        console.log(res.data)
        this.tableData1 = []
        for (let a of res.data.data.total) {
          if (a.settleAccounts == 0) {
            a.settleAccounts = '未结账'
          } else {
            a.settleAccounts = '已结账'
          }
          if (a.affirm == 0) {
            a.affirm = '未确认'
          } else {
            a.affirm = '已确认'
          }
        }
        res.data.data.total.forEach((e) => {
          if (e.recharge == 0) {
            this.tableData1.push(e)
          }
        })
        // this.tableData1 = res.data.data.total
        // this.tableData2 = res.data.data.info
        this.saveList = res.data.data.info
        this.twoList = res.data.data.twoInfoList
      })
    }
  },
  computed: {},
  created() {
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    let operatorVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
    this.operator = operatorVal ? operatorVal[1] : null

    this.inpList = this.getInput() //enter进下一个input框
    this.time = this.searchDateWithHour()
    console.log(this.time)
    this.knhList = this.knhList1
    //店铺销售查询
    console.log(localStorage.getItem('whatState'))
    if (localStorage.getItem('whatState') == '直营') {
      this.isRegular = false
    } else {
      this.isRegular = true
    }
    //获取客户编号
    getShop().then((res) => {
      console.log(res.data)
      this.customerNo = res.data.data.no
    })
  }
}
</script>
